package com.zmzncs.lmtc.module.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.common.pojo.Rest;
import com.zmzncs.lmtc.common.util.ExceptionUtil;
import com.zmzncs.lmtc.common.util.RestUtil;
import com.zmzncs.lmtc.module.system.dao.RoleMapper;
import com.zmzncs.lmtc.module.system.dao.RolePermissionMapper;
import com.zmzncs.lmtc.module.system.dao.UserMapper;
import com.zmzncs.lmtc.module.system.pojo.role.Role;
import com.zmzncs.lmtc.module.system.pojo.role.RoleAddForm;
import com.zmzncs.lmtc.module.system.pojo.role.RoleDTO;
import com.zmzncs.lmtc.module.system.pojo.role.RoleUpdateForm;
import com.zmzncs.lmtc.module.system.pojo.user.UserDTO;
import com.zmzncs.lmtc.module.system.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class RoleIServicempl extends ServiceImpl<RoleMapper, Role> implements RoleService {
	
	@Autowired
    private RoleMapper roleMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
    private RolePermissionMapper rolePermissionMapper;

	/**
	 * 查询角色列表
	 */
	@Override
	public List<RoleDTO> getRoleList() {
		List<RoleDTO> roleVOList = roleMapper.getRoleList();
		return roleVOList;
	}
	
	 /**
	  * 添加角色
	  */
	@Override
	@Transactional
	public void addRole(RoleAddForm addForm){
		RoleDTO roleName = roleMapper.getRoleByName(addForm.getRoleName());
		if(roleName == null) {
			Role role = new Role();
			BeanUtils.copyProperties(addForm, role);
			roleMapper.insert(role);
		}else {
			ExceptionUtil.businessException("角色名称已存在添加无法完成");
		}
		
	}

	/**
	 * 根据角色id查询角色
	 */
	@Override
	public RoleDTO getRoleById(Long id) {
		RoleDTO roleDTO = roleMapper.getRoleById(id);

		return roleDTO;
	}

	/**
	 * 修改角色
	 */
	@Override
	@Transactional
	public void updateRole(RoleUpdateForm updateForm) {
		RoleDTO roleByName = roleMapper.getRoleByName(updateForm.getRoleName());
		RoleDTO roleById = roleMapper.getRoleById(updateForm.getId());
		if(roleByName == null || roleById.getRoleName().equals(updateForm.getRoleName())) {
			Role role = new Role();
			BeanUtils.copyProperties(updateForm, role);
			roleMapper.updateById(role);
		}else {
			ExceptionUtil.businessException("角色名称已存在修改无法完成");
		}

	}

	/**
	 * 删除角色
	 */
	@Override
	@Transactional
	public void deleteRole(Long id) {
		List<UserDTO> userDTOList = userMapper.getUserByRoleId(id);
		if(userDTOList.size() == 0) {
			//删除角色权限关联表
			Role role = new Role();
			role.setId(id);
			role.setIsDeleted(1);
			roleMapper.updateById(role);
		}else {
			ExceptionUtil.businessException("该角色用户被占用，不能删除！");
		}
	}
	
}
